<template>
    <div class="activity-list">
        <el-button type="primary" @click="handleAdd" icon="el-icon-plus" class="add-button">添加动态</el-button>

        <el-table
            :data="activities"
            style="width: 100%"
            border
            class="table"
        >
            <el-table-column prop="id" label="动态ID" width="100"></el-table-column>
            <el-table-column prop="title" label="标题"></el-table-column>
            <el-table-column prop="description" label="描述"></el-table-column>
            <el-table-column prop="date" label="日期" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.date) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <div class="button-group">
                        <el-button
                            size="mini"
                            type="primary"
                            @click="handleEdit(scope.row)"
                            icon="el-icon-edit"
                        >
                            编辑
                        </el-button>
                        <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.row)"
                            icon="el-icon-delete"
                        >
                            删除
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加动态模态框 -->
        <el-dialog v-model="addDialogVisible" title="添加动态" width="50%">
            <el-form :model="newActivity" label-width="100px" :rules="addRules" ref="addForm">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="newActivity.title" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="newActivity.description" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveAdd">保存</el-button>
            </div>
        </el-dialog>

        <!-- 编辑动态模态框 -->
        <el-dialog v-model="editDialogVisible" title="编辑动态" width="50%">
            <el-form :model="currentEdit" label-width="100px" :rules="editRules" ref="editForm">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="currentEdit.title" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="currentEdit.description" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEdit">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
    name: 'ActivityList',
    setup() {
        const token = ref(localStorage.getItem('token'));
        const activities = ref([]);
        const addDialogVisible = ref(false);
        const editDialogVisible = ref(false);
        const newActivity = ref({ title: '', description: '' });
        const currentEdit = ref({});
        const addForm = ref(null);
        const editForm = ref(null);

        const addRules = {
            title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
            description: [{ required: true, message: "描述不能为空", trigger: "blur" }],
        };

        const editRules = {
            title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
            description: [{ required: true, message: "描述不能为空", trigger: "blur" }],
        };

        const fetchActivities = async () => {
            try {
                const response = await axios.get('http://localhost:3008/activities', {
                    headers: { Authorization: `Bearer ${token.value}` },
                });
                activities.value = response.data.data || [];
            } catch (error) {
                console.error('获取动态失败:', error);
                ElMessage.error('获取动态失败，请稍后再试。');
            }
        };

        const handleAdd = () => {
            newActivity.value = { title: '', description: '' };
            addDialogVisible.value = true;
        };

        const saveAdd = async () => {
            try {
                await addForm.value.validate();
                const response = await axios.post('http://localhost:3008/activities', newActivity.value, {
                    headers: { Authorization: `Bearer ${token.value}` },
                });
                if (response.status === 201) {
                    activities.value.push(response.data.data);
                    ElMessage.success('动态添加成功');
                    addDialogVisible.value = false;
                }
            } catch (error) {
                console.error('添加动态失败:', error);
                ElMessage.error(`添加失败: ${error.response?.data?.message || error.message}`);
            }
        };

        const handleEdit = (row) => {
            currentEdit.value = { ...row };
            editDialogVisible.value = true;
        };

        const saveEdit = async () => {
            try {
                await editForm.value.validate();
                const response = await axios.put(`http://localhost:3008/activities/${currentEdit.value.id}`, currentEdit.value, {
                    headers: { Authorization: `Bearer ${token.value}` },
                });
                if (response.status === 200) {
                    const index = activities.value.findIndex(item => item.id === currentEdit.value.id);
                    if (index !== -1) {
                        activities.value[index] = { ...currentEdit.value };
                        ElMessage.success('动态更新成功');
                    }
                    editDialogVisible.value = false;
                }
            } catch (error) {
                console.error('编辑动态失败:', error);
                ElMessage.error(`编辑失败: ${error.response?.data?.message || error.message}`);
            }
        };

        const handleDelete = async (row) => {
            if (confirm(`确定删除动态 "${row.title}" 吗？`)) {
                try {
                    const response = await axios.delete(`http://localhost:3008/activities/${row.id}`, {
                        headers: { Authorization: `Bearer ${token.value}` },
                    });
                    if (response.status === 200) {
                        activities.value = activities.value.filter(item => item.id !== row.id);
                        ElMessage.success('动态删除成功');
                    }
                } catch (error) {
                    console.error('删除动态失败:', error);
                    ElMessage.error(`删除失败: ${error.response?.data?.message || error.message}`);
                }
            }
        };

        const formatDate = (date) => {
            const d = new Date(date);
            return d.toLocaleString();
        };

        onMounted(fetchActivities);

        return {
            activities,
            addDialogVisible,
            editDialogVisible,
            newActivity,
            currentEdit,
            addForm,
            editForm,
            addRules,
            editRules,
            handleAdd,
            saveAdd,
            handleEdit,
            saveEdit,
            handleDelete,
            formatDate,
        };
    },
};
</script>

<style scoped>
.activity-list {
    padding: 20px;
}

.add-button {
    margin-bottom: 20px;
}

.table {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.button-group {
    display: flex;
    gap: 10px;
}
</style>
